package com.gitee.qdbp.general.system.biz.permission.service;

import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.result.ResultCode;
import com.gitee.qdbp.base.model.consts.Keys;
import com.gitee.qdbp.base.system.model.IAccount;
import com.gitee.qdbp.general.system.api.permission.basic.IRoleCoreBasic;
import com.gitee.qdbp.general.system.api.permission.basic.IRoleResourceRefBasic;
import com.gitee.qdbp.general.system.api.permission.model.RoleCoreBean;
import com.gitee.qdbp.general.system.api.permission.model.RoleCoreUpdate;
import com.gitee.qdbp.general.system.api.permission.model.RoleResourceRefWhere;
import com.gitee.qdbp.general.system.api.permission.service.IRoleCoreExecutor;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 角色信息业务处理类
 *
 * @author zhh
 * @version 170215
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public class RoleCoreExecutor implements IRoleCoreExecutor {

    /** 日志对象 **/
    private static final Logger log = LoggerFactory.getLogger(RoleCoreExecutor.class);

    @Autowired
    private IRoleCoreBasic roleCoreBasic;
    @Autowired
    private IRoleResourceRefBasic roleResourceRefBasic;

    @Override
    public void create(RoleCoreBean model, IAccount me) throws ServiceException {
        String msg = "Failed to create RoleCore. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(model)) {
            log.error(msg + "params is null: model");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(model.getRoleName())) {
            log.error(msg + "params is null: RoleName");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        // 获取租户编号:
        // 平台管理员, 允许从输入参数中获取租户编号
        // 租户管理员, 只允许创建本租户的管理员
        String tenantCode = me.getTenantCode();
        if (Keys.ROOT_CODE.equals(me.getTenantCode()) && VerifyTools.isNotBlank(model.getTenantCode())) {
            tenantCode = model.getTenantCode();
        }
        // 设置创建人信息
        model.setTenantCode(tenantCode);
        model.setCreatorId(me.getId()); // 创建人ID
        model.setCreatorName(me.getDisplayName()); // 创建人姓名

        // 向sys_role_core_info表插入记录
        roleCoreBasic.create(model);

    }

    @Override
    public void update(RoleCoreUpdate model, IAccount me) throws ServiceException {
        String msg = "Failed to update RoleCore. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(model)) {
            log.error(msg + "params is null: model");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        String id = model.getId();
        if (VerifyTools.isBlank(id) && model.getWhere() != null) {
            id = model.getWhere().getId();
        }
        if (VerifyTools.isBlank(id)) {
            log.error(msg + "params is null: id");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        // 原始记录检查
        RoleCoreBean older = roleCoreBasic.findById(id);
        if (older == null) {
            log.error(msg + "record is not found. id=" + id);
            throw new ServiceException(ResultCode.RECORD_NOT_EXIST);
        }

        RoleCoreUpdate newer = createChangedModel(model, older);

        if (newer != null) {
            // 更新sys_role_core_info表的记录
            roleCoreBasic.update(newer, false);
        }

    }

    @Override
    public void delete(String id, IAccount me) throws ServiceException {
        String msg = "Failed to delete RoleCore. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(id)) {
            log.error(msg + "params is null: id");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        // 从sys_role_core_info表查询原记录
        RoleCoreBean older = roleCoreBasic.findById(id);
        if (older == null) {
            log.error(msg + "record is not found.\n\tid is " + id);
            throw new ServiceException(ResultCode.RECORD_NOT_EXIST);
        }

        // 删除角色权限关联
        RoleResourceRefWhere where = new RoleResourceRefWhere();
        where.setRoleId(id);
        roleResourceRefBasic.delete(where, false);

        // 删除sys_role_core_info表的记录
        roleCoreBasic.deleteByIds(Arrays.asList(id), false);
    }

    @Override
    public void delete(List<String> ids, IAccount me) throws ServiceException {
        String msg = "Failed to delete RoleCore. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(ids)) {
            log.error(msg + "params is null: ids");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        // 删除角色权限关联
        RoleResourceRefWhere where = new RoleResourceRefWhere();
        where.setRoleIds(ids);
        roleResourceRefBasic.delete(where, false);

        // 删除sys_role_core_info表的记录
        roleCoreBasic.deleteByIds(ids, false);
    }

    /**
     * 创建一个新的对象, 只包含改动过的字段
     *
     * @author zhh
     * @param model 目标对象(一般是参数传入的)
     * @param older 源对象(一般是从数据库查询得到的)
     * @return 只包含有更新的字段对象
     */
    private RoleCoreUpdate createChangedModel(RoleCoreUpdate model, RoleCoreBean older) {
        RoleCoreUpdate newer = new RoleCoreUpdate();
        newer.setWhere(model.getWhere());

        boolean changed = false;
        newer.setId(model.getId()); // 角色ID
        // if (VerifyTools.isChanged(model.getTenantCode(), older.getTenantCode())) {
        //     changed = true;
        //     newer.setTenantCode(model.getTenantCode()); // 租户编号
        // }
        // if (VerifyTools.isChanged(model.getUserType(), older.getUserType())) {
        //     changed = true;
        //     newer.setUserType(model.getUserType()); // 用户类型
        // }
        if (VerifyTools.isChanged(model.getRoleName(), older.getRoleName())) {
            changed = true;
            newer.setRoleName(model.getRoleName()); // 角色名称
        }
        if (VerifyTools.isChanged(model.getRoleDesc(), older.getRoleDesc())) {
            changed = true;
            newer.setRoleDesc(model.getRoleDesc()); // 描述
        }
        if (VerifyTools.isChanged(model.getSortIndex(), older.getSortIndex())) {
            changed = true;
            newer.setSortIndex(model.getSortIndex()); // 排序号(越小越靠前)
        }
        // if (VerifyTools.isChanged(model.getCreatorId(), older.getCreatorId())) {
        //     changed = true;
        //     newer.setCreatorId(model.getCreatorId()); // 创建人ID
        // }
        // if (VerifyTools.isChanged(model.getCreatorName(), older.getCreatorName())) {
        //     changed = true;
        //     newer.setCreatorName(model.getCreatorName()); // 创建人姓名
        // }
        // if (VerifyTools.isChanged(model.getCreateTime(), older.getCreateTime())) {
        //     changed = true;
        //     newer.setCreateTime(model.getCreateTime()); // 创建时间
        // }
        if (VerifyTools.isChanged(model.getDefaults(), older.getDefaults())) {
            changed = true;
            newer.setDefaults(model.getDefaults()); // 默认角色(如果用户没有任何角色,默认会赋予该角色)
        }
        if (VerifyTools.isChanged(model.getOptions(), older.getOptions())) {
            changed = true;
            newer.setOptions(model.getOptions()); // 选项
        }
        // if (VerifyTools.isChanged(model.getDataState(), older.getDataState())) {
        //     changed = true;
        //     newer.setDataState(model.getDataState()); // 数据状态:0为正常|其他为删除
        // }
        // if (Boolean.TRUE.equals(model.isTenantCodeToNull())) {
        //     changed = true;
        //     newer.setTenantCodeToNull(true); // 租户编号更新为空值
        // }
        // if (Boolean.TRUE.equals(model.isUserTypeToNull())) {
        //     changed = true;
        //     newer.setUserTypeToNull(true); // 用户类型更新为空值
        // }
        // if (Boolean.TRUE.equals(model.isRoleNameToNull())) {
        //     changed = true;
        //     newer.setRoleNameToNull(true); // 角色名称更新为空值
        // }
        // if (Boolean.TRUE.equals(model.isRoleDescToNull())) {
        //     changed = true;
        //     newer.setRoleDescToNull(true); // 描述更新为空值
        // }
        // if (Boolean.TRUE.equals(model.isSortIndexToNull())) {
        //     changed = true;
        //     newer.setSortIndexToNull(true); // 排序号(越小越靠前)更新为空值
        // }
        // if (VerifyTools.isNotBlank(model.getSortIndexAdd()) && model.getSortIndexAdd() != 0) {
        //     changed = true;
        //     newer.setSortIndexAdd(model.getSortIndexAdd()); // 排序号(越小越靠前)的增加值
        // }
        // if (Boolean.TRUE.equals(model.isCreatorIdToNull())) {
        //     changed = true;
        //     newer.setCreatorIdToNull(true); // 创建人ID更新为空值
        // }
        // if (Boolean.TRUE.equals(model.isCreatorNameToNull())) {
        //     changed = true;
        //     newer.setCreatorNameToNull(true); // 创建人姓名更新为空值
        // }
        // if (Boolean.TRUE.equals(model.isDefaultsToNull())) {
        //     changed = true;
        //     newer.setDefaultsToNull(true); // 默认角色(如果用户没有任何角色,默认会赋予该角色)更新为空值
        // }
        // if (Boolean.TRUE.equals(model.isOptionsToNull())) {
        //     changed = true;
        //     newer.setOptionsToNull(true); // 选项更新为空值
        // }

        return changed ? newer : null;

    }

}
